/**
 * 后台管理-首页 js
 *
 * @author zhanghua on 15/09/29
 */
$(document).ready(function () {
    /**
     * 动态生成主菜单
     */
    // $.ajax({
    //     type: "POST",
    //     url: '/menu/getMainMenu',
    //     data: {},
    //     success: function (data) {
    //         for (i in data) {
    //             $("#mainMenu").append("<div style='float: left;padding-right: 30px;'><input type='button' onclick=mainMenu('" + data[i].id + "') id='" + data[i].id + "' class='btn1' value='" + data[i].name + "'></div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
    //         }
    //     }
    // });

    $('#workspace').tabs({
        onContextMenu: function (e, title, index) {
            e.preventDefault();
            $('#mm').menu('show', {left: e.pageX, top: e.pageY}).data("tabTitle", title);
        }
    });
    $('#mm').menu({
        onClick: function (item) {
            closeTab(item.name);
        }
    });
    function closeTab(type) {
        $('#workspace').tabs(type);
    }
});

/**
 * 扩展Date，增加格式化日期方法
 *
 * @param format
 * @returns
 */
Date.prototype.formatDate = function (format) {
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
        // millisecond
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};

function onClickMenu(node) {
    if (node.attribute == null) {
        console.log(node.state);
        if ('open' === node.state) {
            $('#menu').tree('collapse', node.target);
        } else {
            $('#menu').tree('expand', node.target);
        }
        return;
    }
    console.trace(node.attribute);
    addEasyuiTab({
        title: node.text,
        href: node.attribute,
        closable: true,
        iconCls: node.iconCls,
        cache: false
    });
}

/**
 * 格式化日期， 默认为yyyy/MM/dd hh:mm:ss
 *
 * @param date
 *            待格式化的日期
 * @param format
 *            日期格式
 * @return 格式化不成功返回undefined
 */
function formatDate(date, format) {
    if (typeof date == "string" && date.trim() == "") {
        return undefined;
    }
    var d = new Date(date);
    // console.log(d);
    if (format) {
        return d.formatDate(format);
    } else {
        return d.formatDate("yyyy/MM/dd hh:mm:ss");
    }
};

// 增加Easyui标签页
function addEasyuiTab(opts, refreshIfExists) {
    var workspace = $('#workspace');
    if ($(workspace).tabs('exists', opts.title)) {
        if (refreshIfExists) {
            if (opts.href && opts.href.indexOf('/') == 0) {
                opts.href = opts.href.substr(1, opts.href.length);
            }
            var tab = $(workspace).tabs('getTab', opts.title);
            $(workspace).tabs('update', {tab: tab, options: {href: opts.href}});
        }
        $(workspace).tabs('select', opts.title);
    } else {
        if (opts.href && opts.href.indexOf('/') == 0) {
            opts.href = opts.href.substr(1, opts.href.length);
        }
        // 清除被easyui动态生成的dialog
        manageUtil.cleanupExtraDialogs(opts);
        $(workspace).tabs('add', opts);
    }
}
/**
 * 关闭Easyui标签页，如果title参数为undefined，关闭当前页
 *
 * @param title
 *            要关闭标签的标题
 */
function closeEasyuiTab(title) {
    var workspace = $('#workspace');
    if (title) {
        $(workspace).tabs('close', title);
    } else {
        var tab = $(workspace).tabs('getSelected');
        var index = $(workspace).tabs('getTabIndex', tab);
        $(workspace).tabs('close', index);
    }
}

/**
 * 将表单中的数据转换成Object
 *
 * @param form jquery对象
 *        option {
 *          allowMulti: boolean // name相同的情况下生成数组, 目前仅处理checkbox和combobox的取值
 *        }
 * @returns {___anonymous1247_1248}
 */
function toObject(form, option) {
    if (!form) {
        return;
    }
    var obj = $(form).data('Object');
    if (!obj) {
        obj = {};
    }
    var inputs = $(form).find('input');
    for (var i = 0, input; input = inputs[i]; i++) {
        if ($(input).prop('type') == 'checkbox') {
            var name = $(input).attr('name');
            if (name) {
                var isChecked = $(input).is(':checked');
                if (option && option.allowMulti == true) {
                    if (isChecked) {
                        if (obj[name] && Array.isArray(obj[name])) {
                            obj[name].push($(input).val());
                        }
                        !obj[name] && (obj[name] = [].concat($(input).val()));
                    }
                } else {
                    obj[name] = isChecked;
                }
            }
            continue;
        }

        if ($(input).prop('type') == 'radio') {
            var name = $(input).attr('name');
            if (name) {
                obj[name] = $("input[name='" + name + "']:checked").val();
            }
            continue;
        }
        if ($(input).hasClass('textbox-value')) {
            continue;
        }
        if ($(input).hasClass('textbox-text')) {
            continue;
        }
        if ($(input).hasClass('textbox-f')) {
            var name = $(input).attr('textboxname');
            if (name) {
                if ($(input).textbox) {
                    var value = $(input).textbox('getValue');
                    // combobox多选支持 feng.yuan on 2016.8.26
                    if ($(input).hasClass('combobox-f') && $(input).combobox('options').multiple) {
                        value = $(input).combobox('getValues');
                    }
                    if (option && option.allowMulti == true && obj[name]) {
                        if (Array.isArray(obj[name])) {
                            obj[name].push(value);
                        } else {
                            obj[name] = [obj[name]].concat(value)
                        }
                    } else {
                        obj[name] = value;
                    }
                } else {
                    obj[name] = $(input).val();
                }
            }
        } else {
            var name = $(input).attr('name');
            if (name) {
                var value = $(input).val();
                if (option && option.allowMulti == true && obj[name]) {
                    if (Array.isArray(obj[name])) {
                        obj[name].push(value);
                    } else {
                        obj[name] = [obj[name]].concat(value)
                    }
                } else {
                    obj[name] = value;
                }
            }
        }
    }
    var selects = $(form).find('select');
    for (var i = 0, select; select = selects[i]; i++) {
        if ($(select).hasClass('combo-f')) {
            var name = $(select).attr('comboname');
            if (name) {
                var usetext = $(select).attr('usetext');
                if (usetext) {
                    obj[name] = $(select).combo('getText');
                } else {
                    obj[name] = $(select).combo('getValue');
                }
            }
        } else {
            var name = $(select).attr('name');
            if (name) {
                obj[name] = $(select).val();
            }
        }
    }
    var textareas = $(form).find('textarea');
    for (var i = 0, textarea; textarea = textareas[i]; i++) {
        var name = $(textarea).attr('name');
        if (name) {
            obj[name] = $(textarea).val();
        }
    }
    return obj;
}

/**
 * 加载中，在耗时任务时务必调用这个方法
 */
function loading() {
    layer.load(2);
}

/**
 * 关闭加载中
 */
function closeLoading() {
    layer.closeAll('loading');
}

/**
 * 系统异常消息
 *
 * @param msg
 *            如果为undefined，显示"系统异常，请稍后重试！"，否则显示msg
 */
function systemErrorMsg(msg) {
    if (msg) {
        layer.msg(msg);
    } else {
        layer.msg('系统异常，请稍后重试！');
    }
}

/**
 * 请求成功消息
 *
 * @param isCloseCurrTab
 *            是否关闭当前页
 */
function okMsg(isCloseCurrTab) {
    layer.msg('完成！');
    if (isCloseCurrTab) {
        closeEasyuiTab();
    }
}

// 公共方法包装
var manageUtil = {};

/**
 * 按条件下载文件
 * options:{
 *   url:'http://www', //请求的url
 *   data:{sc:'xxx'}//要发送的数据
 * });
 */
manageUtil.downloadFile = function (options) {
    var config = $.extend(true, {method: 'post'}, options);
    var $iframe = $('<iframe id="down-file-iframe" />');
    var $form = $('<form target="down-file-iframe" method="' + config.method + '" action="' + config.url + '" />');
    for (var key in config.data) {
        $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
    }
    $iframe.append($form);
    $(document.body).append($iframe);
    $form[0].submit();
    $iframe.remove();
}

/**
 *  清除被easyui动态生成的dialog
 * @param opts
 * @author feng.yuan on 2016-6-15
 */
manageUtil.cleanupExtraDialogs = function (opts) {
    var workspace = $('#workspace');

    // 当新加一个tab时会有额外的div被append到body的最后
    manageUtil.locateLastPanel = manageUtil.locateLastPanel || function () {
            manageUtil.lastPanelUnderBody = $(document.body).children(':last');
        };
    manageUtil.clearPanel = manageUtil.clearPanel || function (title) {
            manageUtil.appendedPanels[title].panel('clear');
            manageUtil.appendedPanels[title].remove();
            manageUtil.locateLastPanel();
        }
    manageUtil.locateLastPanel();
    manageUtil.appendedPanels = manageUtil.appendedPanels || {};
    opts = $.extend(opts, {
        onClose: function (title, index) {
            // 切换tab会调这里的onClose,
            // 在切换回该tab时会将之前tab内相关表单新append到body下的dom清掉然后重新生成(如果在这里清楚所有的新加项会导致该步骤报错)。
            // 在这里要做的是清除不在tab内的(如dialog)相关生成项去掉，之后会重新生成
            manageUtil.clearPanel(opts.title);
            // console.info('opts.onClose:' + opts.title);
        },
        loader: function (queryParams, callback) {
            // hook the loader calling just after panel('clear'), PLEASE DONOT MODIFY
            var th = this;
            manageUtil.rawPanelOptions = manageUtil.rawPanelOptions || $('<div/>').panel().panel("options");
            // jquery.easyui.min.js:formatted #3645
            manageUtil.rawPanelOptions.loader.call(th, queryParams, callback);
            manageUtil.locateLastPanel();
            // console.info($gs.rawPanelOptions);
        }
    });

    // 全局的，关闭tab只能在这里事件处理
    !$(workspace).tabs('options').name && $(workspace).tabs({
        name: 'workspace',
        onLoad: function (panel) {
            var title = panel.panel('options').title,
                lastPanel = manageUtil.lastPanelUnderBody,
                filteredWindows = lastPanel.nextAll('.window');
            filteredWindows = filteredWindows.add(lastPanel.nextAll('.window-shadow'));
            manageUtil.appendedPanels[title] = filteredWindows;
            // console.info('workspace.onLoad:' + title);
        },
        onClose: function (title, index) {
            // 关闭tab会调这里的onClose
            manageUtil.clearPanel(title);
            // console.info('workspace.onClose:' + title);
        }
    });
}

/**
 * add format for console output
 * @author feng.yuan on 2016-7-6
 */
manageUtil.bindDatePrefixWhenConsoleOut = function () {
    var buildParams = function (args, hasFormat) {
        var params = [];
        params.push('%c[%s]%c %c%s' + (hasFormat ? args[0] : ''));
        params.push('color: blue; font-size: 14px;');
        params.push(new Date().toISOString());
        params.push('');
        params.push('background: yellow; font-size: 14px;');
        for (var i = (hasFormat ? 1 : 0); i < args.length; ++i) {
            params.push(args[i]);
        }
        return params;
    };
    ['trace'].forEach(function (methodname) {
        var rawMethod = console[methodname];
        console[methodname] = function () {
            if (arguments.length > 1 && ['%s', '%d', '%i', '%f', '%o', '%c'].some(function (i) {
                    return arguments[0].indexOf(i) != -1
                })) {
                return rawMethod.apply(console, buildParams(arguments, true));
            }
            return rawMethod.apply(console, buildParams(arguments));
        }
    });
}
manageUtil.bindDatePrefixWhenConsoleOut();

/**
 * validate parameters to post
 * prune empty string param with none field & toast tip for wrong date foramt.
 * valid parameter object returned if no invalid parameters.
 * @author feng.yuan on 2016-7-8
 */
manageUtil.isValidParam = function (rawParam) {
    var param = {};
    $.each(rawParam, function (key, val) {
        if (val.length && (key == 'startTime' || key == 'endTime')) {
            if (!isDateTime.call(val, 'yyyy/MM/dd')) {
                layer.msg('时间格式错误');
                param = false;
            }
        }
        if (val.length && !/\s/.test(val)) {
            param[key] = val;
        }
    });

    // 时间起止时间校验
    if (param.startTime && param.endTime &&
        param.startTime.length && param.endTime.length &&
        Date.parse(param.startTime) > Date.parse(param.endTime)) {
        layer.msg('结束时间必须大于开始时间');
        param = false;
    }

    return param;
}

/**
 * custorm event binding using 'click-event' attribute on <a>
 * @author feng.yuan on 2016-7-8
 */
manageUtil.initClickEvents = function (events) {
    for (var evt in events) {
        $('[click-event=' + evt + ']').click((function (cur) {
            return function () {
                events[cur].call(this, arguments)
            }
        })(evt));
    }
}

/**
 * resolve easydatebox placeholder
 * @author feng.yuan on 2016-7-8
 */
manageUtil.resolveDateboxPlaceholder = function () {
    setTimeout(function () {
        $('input[textboxname*=Time]').each(function (index, item) {
            $(item).datebox('textbox').attr('placeholder', $(item).attr('placeholder'));
        });
    }, 10);
}

/**
 * get the unique checked row data
 *
 * @author feng.yuan on 2016-8-10
 */
manageUtil.uniqueRowData = function (datagrid) {
    var row = $(datagrid).datagrid('getSelected');
    var rows = $(datagrid).datagrid('getChecked');
    if (!row || rows.length > 1) {
        layer.msg(!row ? '必须选择一行!' : '只能选择一行!');
        return false;
    }

    return row;
}

/**
 * get the multi checked rows' data
 *
 * @author feng.yuan on 2016-8-24
 */
manageUtil.multiRowData = function (datagrid) {
    var rows = $(datagrid).datagrid('getChecked');
    if (!rows.length) {
        layer.msg('必须至少选择一行!');
        return false;
    }

    return rows;
}

/**
 * toggle dialog by specifying attribute 'action'
 *
 * @author feng.yuan on 2016-8-10
 */
manageUtil.toggleDialog = function (dlgSelector, title, actions) {
    var dlg = $(dlgSelector), options = {}, openDlg = true;
    dlg.form('clear');
    $(this).attr('action').split('|').map(function (action) {
        options[action] = !0;
    })
    for (var action in options) {
        // 只支持两个选项,open|close占一个
        if (action == 'open' || action == 'close') {
            continue;
        }
        if ($.isFunction(actions[action])) {
            openDlg = actions[action].apply($(this), dlg) && openDlg;
            break;
        }
    }
    if (openDlg && options.open) {
        if ($.isFunction(actions.open)) {
            dlg.dialog({
                onOpen: actions.open.bind($(this), dlg)
            });
        }
        if ($.isFunction(actions.close)) {
            dlg.dialog({
                onClose: actions.close.bind($(this), dlg)
            });
        }
        dlg.dialog("setTitle", title).dialog("center").dialog("open");
    } else {
        dlg.dialog("close");
    }
    return dlg;
}
